package server;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import database.local.Business;
import database.local.CheckIn;
import database.local.Comment;
import database.local.Deal;
import database.local.Likes;
import database.local.User;


public class SaveZoneHttpConnection {
	
	/*url connections*/
	public static final String MAIN_URL = 							"http://workshop-team-5.appspot.com/";
	public static final String DATA_BASE_QUERY_SUFFIX = 			"database/query";
	public static final String DATA_BASE_USER_QUERY_SUFFIX = 		"database/query/user";
	public static final String DATA_BASE_ADD_SUFFIX = 				"database/add";
	public static final String DATA_BASE_DEAL_DELETE_SUFFIX = 		"database/add/delete";
	public static final String DATA_BASE_RATE_DEAL_SUFFIX = 		"database/rate/deal";
	public static final String DATA_BASE_RATE_COMMENT_SUFFIX = 		"database/rate/comment";
	public static final String DATA_BASE_COMMENT_SUFFIX = 			"database/comment";
	public static final String DATA_BASE_FAKE_DEAL_SUFFIX = 		"database/rate/deal/fake";
	public static final String DATA_BASE_USER_LIKES_GET_SUFFIX = 	"likes/get";
	public static final String DATA_BASE_USER_LIKES_SET_SUFFIX = 	"likes/set";
	public static final String DATA_BASE_CHECKIN_SET_SUFFIX = 		"checkin/set";
	public static final String DATA_BASE_CHECKIN_GET_SUFFIX = 		"checkin/get";
	public static final String DATA_BASE_USER_LIKES_FACEBOOK_SET_SUFFIX = "likes/facebook_set";
	/*deal days bitmap*/
	public static final int MONDAY = 0x1;
	public static final int TUESDAY = 0x2;
	public static final int WEDNESDAY = 0x4;
	public static final int THURSDAY = 0x8;
	public static final int FRIDAY = 0x10;
	public static final int SATURDAY = 0x20;
	public static final int SUNDAY = 0x40;
	public static final int ALL_DAYS = 0x7F;
	
	
	/**
	 * 
	 * @param data includes all the parameters for the search in the database
	 * @return InputStream of the xml
	 */
	public static InputStream query(Map<String, String> data){
		return post(data, DATA_BASE_QUERY_SUFFIX);
	}
	
	public static InputStream user_query(Map<String, String> data) {
		return post(data, DATA_BASE_USER_QUERY_SUFFIX);
	}
	
	/**
	 * 
	 * @param data includes xml
	 * @return InputStream of the xml
	 */
	public static InputStream add(List<Business> business_lst, User user) {
		String xml = XmlParser.produceXmlPage(business_lst);
		Map<String, String> data = new HashMap<String, String>();
		//System.out.println(xml);
		data.put("xml", xml);
		data.put("email", user.getEmail());
		data.put("user_name", user.getUser_name());
		return post(data, DATA_BASE_ADD_SUFFIX);
	}
	
	/**
	 * post the parameters in data according to the url_suffix
	 * @param data
	 * @param url_suffix
	 * @return
	 */
	private static InputStream post(Map<String, String> data, String url_suffix){
		try {
            // Send the request
            URL url = new URL(MAIN_URL + url_suffix);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
            
            //convert data
            Set<Entry<String, String>> data_set = data.entrySet();
            Iterator<Entry<String, String>> iterator = data_set.iterator();
            StringBuilder data_post = new StringBuilder();
            while (iterator.hasNext()) {
            	Entry<String, String> elem = iterator.next();
            	data_post.append(elem.getKey() + "=" + elem.getValue().replace("&", " "));
            	if (iterator.hasNext())
            		data_post.append("&");
            }
            String data_post_str = data_post.toString();
            if (data.isEmpty())
            	data_post_str = "";
            //System.out.println(data_post_str);
            //write parameters
            writer.write(data_post_str);
            writer.flush();
            InputStream reader = conn.getInputStream();
            return reader;
            //Output the response
            
            
        } catch (MalformedURLException ex) {
            return null;
        } catch (IOException ex) {
            return null;
        }
	
	}

	public static boolean checkResult(InputStream stream) {
		String result = XmlParser.getResult(stream);
		
		if (result != null && result.matches("success")) return true;
		return false;
	}

	
	
	/************
	 * comment deals
	 * @param cost_level 
	 * @param rate 
	 */
	public static void commentDeal(Deal deal, String comment_str, int rate, int cost_level, User user) {
		String xml = XmlParser.dealToXml(deal); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("user_name", user.getUser_name());
		data.put("email", user.getEmail());
		data.put("comment", comment_str);
		data.put("rate", String.valueOf(rate));
		data.put("cost_level", String.valueOf(cost_level));
		
		post(data, DATA_BASE_COMMENT_SUFFIX);
		
	}
	
	/************
	 *rate objects
	 */
	public static void rateDeal(Deal deal, int rate) {
		String xml = XmlParser.dealToXml(deal); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("rate", String.valueOf(rate));
		
		post(data, DATA_BASE_RATE_DEAL_SUFFIX);
		
	}
	
	public static void rateComment(Comment comment, int rate) {
		String xml = XmlParser.commentToXml(comment); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("rate", String.valueOf(rate));
		
		post(data, DATA_BASE_RATE_COMMENT_SUFFIX);
		
	}

	public static void costLevelDeal(Deal deal, int cost_level) {
		String xml = XmlParser.dealToXml(deal); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("cost_level", String.valueOf(cost_level));
		
		post(data, DATA_BASE_RATE_DEAL_SUFFIX);
		
	}

	public static void reportFakeDeal(User user, Deal deal) {
		String xml = XmlParser.dealToXml(deal); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("user_name", user.getUser_name());
		data.put("email", user.getEmail());
		
		post(data, DATA_BASE_FAKE_DEAL_SUFFIX);
		
	}

	public static void deleteDeal(Deal deal, User user) {
		String xml = XmlParser.dealToXml(deal); 
		Map<String, String> data = new HashMap<String, String>();
		data.put("xml", xml);
		data.put("user_name", user.getUser_name());
		data.put("email", user.getEmail());
		
		post(data, DATA_BASE_DEAL_DELETE_SUFFIX);
	}

	public static List<CheckIn> getCheckInList(Business business) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("business", business.getKey());
		
		InputStream stream = post(data, DATA_BASE_CHECKIN_GET_SUFFIX);
		if (stream != null) {
			return XmlParser.getCheckInList(stream);
		} else {
			return new ArrayList<CheckIn>();
		}
	}

	public static void checkIn(Business business, String user_name, String email, String pic, String facebook_link) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("business", business.getKey());
		data.put("user_name", user_name);
		data.put("email", email);
		data.put("pic", pic);
		data.put("facebook_link", facebook_link);
		post(data, DATA_BASE_CHECKIN_SET_SUFFIX);
	}

	public static Likes getLikeList(User user) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("email", user.getEmail());
		data.put("user_name", user.getUser_name());
		
		InputStream stream = post(data, DATA_BASE_USER_LIKES_GET_SUFFIX);
		if (stream != null) {
			return XmlParser.getLikesList(stream);
		} else {
			return new Likes();
		}
	}

	public static void likeDeal(User user, int deal_type) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("email", user.getEmail());
		data.put("user_name", user.getUser_name());
		data.put("deal_type", String.valueOf(deal_type));
		post(data, DATA_BASE_USER_LIKES_SET_SUFFIX);
	}

	public static void sendFacebookLikes(User user, List<String> likes) {
		String data_str = "";
		for (String string : likes) {
			data_str += string + "#";
		}
		Map<String, String> data = new HashMap<String, String>();
		data.put("data_str", data_str);
		data.put("email", user.getEmail());
		data.put("user_name", user.getUser_name());
		post(data, DATA_BASE_USER_LIKES_FACEBOOK_SET_SUFFIX);
	}


}

